import {
  registerMicroApps,
  start,
  initGlobalState,
  // addGlobalUncaughtErrorHandler,
  // setDefaultMountApp
} from "qiankun";

import store from "@/store";
import router from "@/router";
import { log, commonApi } from "@/api";
import jsoneditor from "jsoneditor";


const { onGlobalStateChange, setGlobalState } = initGlobalState({
  userInfo: {},
});

// 父应用和微应用通信
onGlobalStateChange((data) => {
  if (data.loading !== undefined) {
    store.commit("loading", data.loading);
  }
});

const getActiveRule = (hash) => (location) => location.hash.startsWith(hash);
// 注册微应用
export async function initMicroApp(resource) {
  let appsConfig = resource.map((item, i) => {
    let { name, meta } = item;
    return {
      icon: meta.icon,
      name,
      title: meta.title,
      entry:
        process.env.NODE_ENV === "development"
          ? item.meta.entry
          : `${location.origin}/${name}/`,
      activeRule: getActiveRule(`#/${name}`),
      container: "#micro_app",
      appType: meta.appType,
    };
  });

  let apps = [];
  appsConfig.forEach((item) => {
    if (item.appType !== "iframe") {
      apps.push({
        ...item,
        props: {
          commonApi,
          jsoneditor
        },
      });
    }
  });
  console.log(apps)
  registerMicroApps(apps);
  resource = resource.map((item) => {
    return {
      ...item,
      component: () =>
        import(/* webpackChunkName: "Layout" */ "./views/Layout.vue"),
    };
  });
  router.addRoutes(resource);
  start({ sandbox: false });
}

export function setGlobalData(state) {
  setGlobalState({ ...state, curRoute: { name: "", params: {} } });
}

// 权限管控
router.beforeEach(async (to, from, next) => {
  console.log(to.name)
  if (to.path === from.path) {
    return;
  }
  // 是否为主应用的默认路由
  if (to.meta && to.meta.isDefault) {
    next();
    return;
  }

  let str = localStorage.getItem("userInfo");
  let userInfo;
  if (str) {
    userInfo = JSON.parse(str);
  }

  // 是否已经登录过
  if (!userInfo) {
    if (to.name === "Login") {
      next();
    } else {
      next({
        path: "/Login",
      });
      return;
    }
  } else if (!store.getters.userInfo.id && userInfo) {
    store.commit("userInfo", userInfo);
    setGlobalState({
      userInfo,
    });
    await store.dispatch("getResource");
    router.push({
      ...to
    });
    return;
  }

  if (to.matched.length == 0) {
    next({
      path: "/404",
    });
  } else {
    next();
    let system = to.matched[0].meta.title;
    let module = to.meta.title ? to.meta.title : to.name;
    if (system && module && system !== module) {
      log({
        system,
        module,
        type: "系统访问",
        info: `访问${system}系统,${module}模块`,
      });
    }
  }
});
